package com.huifaapp.mall.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.ReceiveAddressAdapter;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.ReceiveBean;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.Contig;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ReceiveAddressActivity extends AppCompatActivity {

    private Button address;
    private RecyclerView receive_Recy;
    private ReceiveAddressAdapter receiveAddressAdapter;
    private ImageView im_add;
    private List<ReceiveBean.DataBean> lists;
    private ImageView iv_forgot_password_back;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_address);
        initView();
        loadData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1010) {
            loadData();
        }
    }

    /*
    * 获取网络数据
    * */
    private void loadData() {
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"users/address/addrlist")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(this))
                //?token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        initData(response);
                    }
                });
    }


    private void initView() {
        address = (Button) findViewById(R.id.Buttonaddress);
        address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ReceiveAddressActivity.this, DeliveryActivity.class);
                intent.putExtra("idid",2+"");
                startActivityForResult(intent, 1010);

            }
        });
        iv_forgot_password_back= (ImageView) findViewById(R.id.iv_forgot_password_back);
        iv_forgot_password_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        receive_Recy = (RecyclerView) findViewById(R.id.receive_addressrecy);
        im_add = (ImageView) findViewById(R.id.receive_add);


//            receive_Recy.setVisibility(View.VISIBLE);

//            im_add.setVisibility(View.GONE);



        receive_Recy.setLayoutManager(new LinearLayoutManager(this));

    }

    @Override
    protected void onResume() {
        super.onResume();
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"users/address/addrlist")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(this))
                //?token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        initData(response);
                    }
                });

    }

    private void initData(String response) {

        Gson gson = new Gson();
        ReceiveBean receiveBean = gson.fromJson(response, ReceiveBean.class);
        lists = receiveBean.getData();
        receiveAddressAdapter = new ReceiveAddressAdapter(this, lists);
        receive_Recy.setAdapter(receiveAddressAdapter);
        receiveAddressAdapter.setAdapterClickListener(new ReceiveAddressAdapter.onAdapterItemClickListener() {
            @Override
            public void onClick(View view, final int position) {
                lists = receiveAddressAdapter.getAdapterData();
                final   List<ReceiveBean.DataBean> list = receiveAddressAdapter.getAdapterData();
//                for (int i = 0; i < list.size(); i++) {
//                    list.get(i).setIsDefaultAddress("0");
                list.get(position).setIsDefaultAddress("0");
                final String id = lists.get(position).getId();
//                    final int finalI = i;
                OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL+"users/address/addDefaultAddr")
                        .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                        .addParams("appId", AUniqueIdentifier.getDeviceId(ReceiveAddressActivity.this))
                        .addParams("addrId", id)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Request request, Exception e) {
                                e.printStackTrace();
                            }
                            @Override
                            public void onResponse(String response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String code = jsonObject.getString("code");
                                    if (code.equals("10000")) {
                                        ToastUtils.showShort("修改成功");
                                        for (int i = 0; i < list.size(); i++) {
                                            list.get(i).setIsDefaultAddress("0");
                                        }list.get(position).setIsDefaultAddress("1");
                                        receiveAddressAdapter.notifyDataSetChanged();


                                    } else {
                                        ToastUtils.showShort("修改失败");
                                    }
                                } catch (JSONException e1) {
                                    e1.printStackTrace();
                                }

                            }
                        });
            }
//                list.get(position).setIsDefaultAddress("1");
//                receiveAddressAdapter.notifyDataSetChanged();



        });
        receiveAddressAdapter.setOnItemClickListener(new ReceiveAddressAdapter.OnItemClickListener() {
            @Override
            public void onDelete(final int position) {
                AlertDialog alertDialog = new AlertDialog.Builder(ReceiveAddressActivity.this).setTitle("提示").setMessage("是否需要删除？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                final String  addr = lists.get(position).getId();
                                OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL+"users/address/del")
                                        .addParams("addrId", addr)
                                        .build()
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onError(Request request, Exception e) {
                                                ToastUtils.showShort("删除失败");
                                            }

                                            @Override
                                            public void onResponse(String response) {

                                                Log.e("HB", response);
                                                try {
                                                    JSONObject jsonObject = new JSONObject(response);
                                                    String code = jsonObject.getString("code");
                                                    if (code.equals("10000")) {
                                                        lists.remove(position);
                                                        if (lists.size() > 0) {
                                                            im_add.setVisibility(View.GONE);
                                                            receive_Recy.setVisibility(View.VISIBLE);

                                                        } else {
                                                            im_add.setVisibility(View.VISIBLE);
                                                            receive_Recy.setVisibility(View.GONE);
                                                        }
                                                        receiveAddressAdapter.notifyDataSetChanged();

                                                    } else {
                                                        ToastUtils.showShort("删除失败");
                                                    }

                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }

                                            }
                                        });


                            }
                        }).create();
                alertDialog.show();
            }

            @Override
            public void onBianji(int position) {
                final ReceiveBean.DataBean dataBean = lists.get(position);
                final String  addrs = lists.get(position).getId();
                Intent intent = new Intent(ReceiveAddressActivity.this,DeliveryActivity.class);
                intent.putExtra("addrId",addrs);
                intent.putExtra("idid",1+"");
                intent.putExtra("name",dataBean.getReceiverName());
                intent.putExtra("phone",dataBean.getReceiverPhone());
                intent.putExtra("city",dataBean.getCity());
                intent.putExtra("xiangxi",dataBean.getDetail());
                intent.putExtra("moren",dataBean.getIsDefaultAddress());
                startActivity(intent);

            }

            @Override
            public void onIntentadree(int position) {
                final ReceiveBean.DataBean dataBean = lists.get(position);
                Contig.name=dataBean.getReceiverName();
                Contig.phone=dataBean.getReceiverPhone();
                Contig.city=dataBean.getCity()+" "+dataBean.getDetail();
                Log.e("地址地址",dataBean.getReceiverName()+"   "+dataBean.getReceiverPhone()+"  "+dataBean.getCity()+" "+dataBean.getDetail()+"" );
                Intent intent = new Intent();
                intent.putExtra("names",dataBean.getReceiverName());
                intent.putExtra("phones",dataBean.getReceiverPhone());
                intent.putExtra("citys",dataBean.getCity()+" "+dataBean.getDetail());
                intent.putExtra("ids",dataBean.getId());
                setResult(1021, intent);
                finish();
            }
        });
        lists = receiveBean.getData();
        if (lists == null) {
            lists = new ArrayList<>();
        }
        Log.e("jijijiji",""+lists);
        if (lists.size() > 0) {
            im_add.setVisibility(View.GONE);
            receive_Recy.setVisibility(View.VISIBLE);

        } else {
            im_add.setVisibility(View.VISIBLE);
            receive_Recy.setVisibility(View.GONE);
        }
        receiveAddressAdapter.addorder(lists);
        receiveAddressAdapter.notifyDataSetChanged();
    }
}
